package controllers

import (
	"go_wep_demo/common"
	"go_wep_demo/logic"
	"go_wep_demo/models"
	"go_wep_demo/pkg/jwt"

	"github.com/gin-gonic/gin"
)

// SignUpHandler 注册接口
// @Summary 用户注册
// @Description 用户注册
// @Tags 用户相关
// @Accept application/json
// @Produce application/json
// @Param object body models.ParamSignUp true "post参数"
// @Success 200 {object} _ResponseSignUp
// @Router /signup [post]
func SignUpHandler(c *gin.Context) {
	//1、参数校验
	var data = new(models.ParamSignUp)
	err := c.ShouldBind(data)
	if err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParam, GetErrorMsg(err))
		return
	}
	//2、业务处理
	err = logic.SignUp(data)
	if err != nil {
		ResponseErrorWithMsg(c, CodeSignUpError, err.Error())
		return
	}
	//3、返回响应
	ResponseSuccess(c, nil)
}

func LoginHandler(c *gin.Context) {
	var err error
	//1、参数校验
	var data = new(models.ParamLogin)
	err = c.ShouldBind(data)
	if err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParam, GetErrorMsg(err))
		return
	}
	//2、业务处理
	var loginStruct models.LoginStruct
	loginStruct, err = logic.Login(data)
	if err != nil {
		ResponseErrorWithMsg(c, CodeLoginError, err.Error())
		return
	}
	//3、返回响应
	ResponseSuccess(c, loginStruct)
}

func RefreshTokenHandler(c *gin.Context) {
	aToken := c.Request.Header.Get(common.TokenKey)
	rToken := c.Request.Header.Get(common.RefreshTokenKey)
	newAToken, newRToken, err := jwt.RefreshToken(aToken, rToken)
	if err != nil {
		ResponseError(c, CodeNeedLogin)
	}
	loginStruct := models.LoginStruct{
		Token:        newAToken,
		RefreshToken: newRToken,
	}
	ResponseSuccess(c, loginStruct)
}
